package cn.webrx.bs.servlet;

import cn.webrx.bs.entity.Ad;
import cn.webrx.bs.service.AdDao;
import cn.webrx.bs.service.AdDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * <p>功能描述: </p>
 *
 * @author webrx
 * @version 1.0
 * @date 2020-08-14 17:35
 */
@WebServlet("/admin/ad") @MultipartConfig
public class AdminAd extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String action = req.getParameter("action");
        if ("add".equals(action)) {
            //接文件存项目指定的目录
            Part img = req.getPart("img");
            String fn = img.getSubmittedFileName();
            System.out.println(fn);
            System.out.println(img.getSize());
            String ext = fn.substring(fn.lastIndexOf(".")).toLowerCase();
            Random rand = new Random();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String newfile = String.format("%s_%06d",sdf.format(new Date()),rand.nextInt(99999))+ext;
            String path = req.getServletContext().getRealPath("/upload/ad/");
            try {
                FileOutputStream fos = new FileOutputStream(path+"/"+newfile);
                fos.write(img.getInputStream().readAllBytes());
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            //接表单存储数据库

            AdDao addao =  new AdDaoImpl();
            Ad ad = new Ad();
            ad.setCdt(new Date());
            ad.setImg(newfile);
            ad.setUrl(req.getParameter("url"));
            ad.setTitle(req.getParameter("title"));
            ad.setSort(Integer.parseInt(req.getParameter("sort")));
            String i = req.getParameter("isshow"); //如果没有选中，传null，如果选中传1
            ad.setShows(i==null?false:true);
            addao.add(ad);

            //req.getRequestDispatcher("/admin/admanager.ftl").forward(req, resp);
        }else if ("editupdate".equals(action)) {
            int id = Integer.parseInt(req.getParameter("id"));
            int sort = Integer.parseInt(req.getParameter("sort"));
            String title = req.getParameter("title");
            String url = req.getParameter("url");
            boolean shows = req.getParameter("isshow") == null ? false : true;
            Ad ad = new Ad();
            ad.setShows(shows);
            ad.setId(id);
            ad.setTitle(title);
            ad.setUrl(url);
            ad.setSort(sort);
            AdDao addao = new AdDaoImpl();
            addao.update(ad);
            //如果上传
            Part part = req.getPart("img");
            if(part.getSize()>0){
                String path = req.getServletContext().getRealPath("/upload/ad/");
                try {
                    FileOutputStream fos = new FileOutputStream(path+"/"+req.getParameter("oldimg"));
                    fos.write(part.getInputStream().readAllBytes());
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            resp.sendRedirect("/admin/ad?action=manager");
        }else if ("delete".equals(action)) {
            AdDao addao = new AdDaoImpl();
            int id = Integer.parseInt(req.getParameter("id"));
            String url = req.getServletContext().getRealPath("/upload/ad/"+req.getParameter("img"));
            addao.deleteById(id,url);
            resp.sendRedirect("/admin/ad?action=manager");
        }else if ("edit".equals(action)) {
            int id = Integer.parseInt(req.getParameter("id"));
            AdDao addao = new AdDaoImpl();
            req.setAttribute("ad",addao.queryById(id));
            req.getRequestDispatcher("/admin/adedit.ftl").forward(req, resp);
        }else if ("shows".equals(action)) {
            int id = Integer.parseInt(req.getParameter("id"));
            String shows = req.getParameter("shows");
            AdDao addao = new AdDaoImpl();
            addao.update(id,"true".equals(shows));
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().print("true".equals(shows) ? "显示" : "隐藏");
        }else if ("manager".equals(action)) {
            req.setAttribute("ads",new AdDaoImpl().queryAll());
            req.getRequestDispatcher("/admin/admanager.ftl").forward(req, resp);
        }else{
            req.getRequestDispatcher("/admin/ad.ftl").forward(req, resp);
        }
    }
}
